package com.plum.admin.config.interceptor;

import cn.hutool.core.util.StrUtil;
import com.google.gson.Gson;
import com.plum.admin.common.constant.Constant;
import com.plum.admin.common.util.ResponseUtil;
import com.plum.admin.common.vo.TokenUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 子丶沫
 */
@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String header = request.getHeader(Constant.HEADER);
        if(StrUtil.isBlank(header)){
            header=request.getParameter(Constant.HEADER);
        }
        Boolean noValid=StrUtil.isBlank(header)||(!header.startsWith(Constant.TOKEN_SPLIT));
        if(noValid){
            return true;
        }
        String user = redisTemplate.opsForValue().get(Constant.TOKEN_PRE + header.split(" ")[1]);
        if(StrUtil.isBlank(user)){
            return true;
        }
        TokenUser tokenUser = new Gson().fromJson(user, TokenUser.class);
        String token=header.split(" ")[1];
        String oldToken = redisTemplate.opsForValue().get(Constant.USER_TOKEN + tokenUser.getUsername());
        if(StrUtil.isNotBlank(oldToken)&&oldToken.equals(token)){
            ResponseUtil.out(response,ResponseUtil.resultMap(401,"您的账号已在其他地方登录，请重新登录"));
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
